package org.budo.phone.ronglian;

import org.budo.phone.api.request.IvrDialRequest;
import org.budo.phone.api.request.QueryAgentStateRequest;
import org.budo.phone.api.response.IvrDialResponse;
import org.budo.phone.api.response.QueryAgentStateResponse;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.lang.util.NumberUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.time.Time;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Getter
@Setter
@Slf4j
public class BudoRonglianPhoneApi extends AbstractRonglianPhoneApi {
    @Override
    public IvrDialResponse ivrDial(IvrDialRequest ivrDialRequest) {
        String time = Time.now().toString("yyyyMMddHHmmss");

        String accountSid = this.getAccountSid();

        String authorizationLine = accountSid + ":" + time;
        String authorizationBase64 = Base64Utils.encodeToString(authorizationLine.getBytes());

        String sigLine = accountSid + this.getAccountToken() + time;
        String sigMd5 = DigestUtils.md5DigestAsHex(sigLine.getBytes());

        String userdata = ivrDialRequest.getUserdata();
        String number = ivrDialRequest.getNumber();
        String disnumber = ivrDialRequest.getDisnumber();
        String record = ivrDialRequest.getRecord();
        String appId = ivrDialRequest.getAppId();

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //
                "<Request>" + //
                "  <Appid>" + appId + "</Appid>" + //
                "  <Dial number=\"" + number + "\" disnumber=\"" + disnumber + "\" userdata=\"" + userdata + "\" record=\"" + record + "\"></Dial>" + //
                "</Request>";

        Request request = new Request();
        request.setUrl(this.getRestUrl() + "/Accounts/" + accountSid + "/ivr/dial?sig=" + sigMd5);
        request.setHeader("Authorization", authorizationBase64);
        request.setContentType("application/xml");
        request.setMethod(Request.POST);
        request.setRequestBody(xml);
        Response response = request.execute();

        Integer responseStatus = response.getStatus();
        String responseBody = response.getBody();
        if (!NumberUtil.equals(200, responseStatus) || StringUtil.isEmpty(responseBody)) {
            log.error("#58 ivrDial, responseBody=" + responseBody + ", request=" + request);

            return new IvrDialResponse() //
                    .setStatusCode("api-status-" + responseStatus);
        }

        log.info("#53 ivrDial, responseBody=" + responseBody + ", request=" + request);

        JSONObject jsonObject = JSON.parseObject(responseBody);
        String statusCode = jsonObject.getString("statusCode");
        String callId = jsonObject.getString("callId");

        return new IvrDialResponse() //
                .setStatusCode(statusCode).setCallId(callId);
    }

    /**
     * https://doc.yuntongxun.com/p/5a534cde3b8496dd00dce22d
     */
    @Override
    public QueryAgentStateResponse queryAgentState(QueryAgentStateRequest queryAgentStateRequest) {
        String time = Time.now().toString("yyyyMMddHHmmss");

        String accountSid = this.getAccountSid();

        String authorizationLine = accountSid + ":" + time;
        String authorizationBase64 = Base64Utils.encodeToString(authorizationLine.getBytes());

        String sigLine = accountSid + this.getAccountToken() + time;
        String sigMd5 = DigestUtils.md5DigestAsHex(sigLine.getBytes());

        String agentId = queryAgentStateRequest.getAgentId();
        String appId = queryAgentStateRequest.getAppId();

        String xml = "<?xml version='1.0' encoding='utf-8'?>" + //
                "<Request>" + //
                "  <Appid>" + appId + "</Appid>" + //
                "  <QueryAgentState agentid='" + agentId + "'/>" + //
                "</Request>";

        Request request = new Request();
        request.setUrl("http://fs.taojinykf.com/freeswitch/Accounts/" + accountSid + "/ivr/queryagentstate?sig=" + sigMd5);
        request.setHeader("Authorization", authorizationBase64);
        request.setContentType("application/xml");
        request.setMethod(Request.POST);
        request.setRequestBody(xml);
        Response response = request.execute();

        log.info("#92 queryAgentState, response=" + response);
        return new QueryAgentStateResponse();
    }
}